import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { v4 as uuidv4 } from 'uuid';

// 定义节点类型
export const NodeTypes = {
  START: 'start',
  CONDITION: 'condition',
  LOOP: 'loop',
  ACTION: 'action',
  END: 'end'
};

// 定义流程图存储
export const useFlowStore = defineStore('flow', () => {
  // 流程图节点和边的状态
  const nodes = ref([]);
  const edges = ref([]);
  const selectedElements = ref([]);
  const history = ref([]);
  const historyIndex = ref(-1);
  
  // 生成的代码
  const generatedCode = ref('');
  
  // 计算属性：是否可以撤销/重做
  const canUndo = computed(() => historyIndex.value > 0);
  const canRedo = computed(() => historyIndex.value < history.value.length - 1);
  
  // 添加节点
  function addNode(nodeData) {
    const newNode = {
      id: uuidv4(),
      type: nodeData.type,
      position: nodeData.position,
      data: nodeData.data || {}
    };
    
    nodes.value.push(newNode);
    saveToHistory();
    return newNode;
  }
  
  // 添加连接线
  function addEdge(edgeData) {
    const newEdge = {
      id: uuidv4(),
      source: edgeData.source,
      target: edgeData.target,
      sourceHandle: edgeData.sourceHandle,
      targetHandle: edgeData.targetHandle,
      label: edgeData.label || ''
    };
    
    edges.value.push(newEdge);
    saveToHistory();
    return newEdge;
  }
  
  // 更新节点
  function updateNode(nodeId, newData) {
    const nodeIndex = nodes.value.findIndex(node => node.id === nodeId);
    if (nodeIndex !== -1) {
      nodes.value[nodeIndex] = { ...nodes.value[nodeIndex], ...newData };
      saveToHistory();
    }
  }
  
  // 更新边
  function updateEdge(edgeId, newData) {
    const edgeIndex = edges.value.findIndex(edge => edge.id === edgeId);
    if (edgeIndex !== -1) {
      edges.value[edgeIndex] = { ...edges.value[edgeIndex], ...newData };
      saveToHistory();
    }
  }
  
  // 删除节点
  function removeNode(nodeId) {
    nodes.value = nodes.value.filter(node => node.id !== nodeId);
    // 同时删除与该节点相关的边
    edges.value = edges.value.filter(
      edge => edge.source !== nodeId && edge.target !== nodeId
    );
    saveToHistory();
  }
  
  // 删除边
  function removeEdge(edgeId) {
    edges.value = edges.value.filter(edge => edge.id !== edgeId);
    saveToHistory();
  }
  
  // 选择元素
  function selectElements(elements) {
    selectedElements.value = elements;
  }
  
  // 保存当前状态到历史记录
  function saveToHistory() {
    // 如果当前不是最新状态，则删除当前索引之后的所有历史记录
    if (historyIndex.value < history.value.length - 1) {
      history.value = history.value.slice(0, historyIndex.value + 1);
    }
    
    // 保存当前状态的深拷贝
    history.value.push({
      nodes: JSON.parse(JSON.stringify(nodes.value)),
      edges: JSON.parse(JSON.stringify(edges.value))
    });
    
    historyIndex.value++;
  }
  
  // 撤销操作
  function undo() {
    if (canUndo.value) {
      historyIndex.value--;
      const prevState = history.value[historyIndex.value];
      nodes.value = JSON.parse(JSON.stringify(prevState.nodes));
      edges.value = JSON.parse(JSON.stringify(prevState.edges));
    }
  }
  
  // 重做操作
  function redo() {
    if (canRedo.value) {
      historyIndex.value++;
      const nextState = history.value[historyIndex.value];
      nodes.value = JSON.parse(JSON.stringify(nextState.nodes));
      edges.value = JSON.parse(JSON.stringify(nextState.edges));
    }
  }
  
  // 生成JavaScript代码
  function generateCode() {
    // 这里将实现代码生成逻辑
    // 暂时返回一个简单的示例
    generatedCode.value = '// 生成的代码将显示在这里\n';
    
    // 实际的代码生成将在后续实现
  }
  
  // 清空流程图
  function clearFlow() {
    nodes.value = [];
    edges.value = [];
    saveToHistory();
  }
  
  // 导出流程图数据
  function exportFlow() {
    return {
      nodes: nodes.value,
      edges: edges.value
    };
  }
  
  // 导入流程图数据
  function importFlow(flowData) {
    if (flowData && flowData.nodes && flowData.edges) {
      nodes.value = flowData.nodes;
      edges.value = flowData.edges;
      saveToHistory();
    }
  }
  
  return {
    nodes,
    edges,
    selectedElements,
    generatedCode,
    canUndo,
    canRedo,
    addNode,
    addEdge,
    updateNode,
    updateEdge,
    removeNode,
    removeEdge,
    selectElements,
    undo,
    redo,
    generateCode,
    clearFlow,
    exportFlow,
    importFlow
  };
});